package com.taptech.doufu.ui.activity.story

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.taptech.doufu.R
import com.taptech.doufu.bean.TagBean
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.SPKey
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.constant.UmengEventName
import com.taptech.doufu.ktexpand.format
import com.taptech.doufu.model.novel.bean.NovelCommentBean
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.presenter.novel.IStoryDetailsView
import com.taptech.doufu.presenter.novel.StoryDetailsPresenter
import com.taptech.doufu.services.HomeMainServices
import com.taptech.doufu.services.history.ReadHistoryUtil
import com.taptech.doufu.services.history.ReadRecord
import com.taptech.doufu.services.personalcenter.AccountService
import com.taptech.doufu.ui.activity.BrowseActivity
import com.taptech.doufu.ui.activity.StoryPosterActivity
import com.taptech.doufu.ui.activity.UserDetailActivity
import com.taptech.doufu.ui.activity.base.BaseMvpActivity
import com.taptech.doufu.ui.adapter.NovelHotCommentAdapter
import com.taptech.doufu.util.*
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences
import kotlinx.android.synthetic.main.activity_story_detail.*
import kotlinx.android.synthetic.main.view_share_enter.*
import kotlinx.android.synthetic.main.view_story_detail_bottom.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap


class StoryDetailsActivity :BaseMvpActivity<StoryDetailsPresenter>(),IStoryDetailsView{

    private var commentAdapter:NovelHotCommentAdapter? = null
    private var shareDialog: BottomSheetDialog? = null
    private var isYouthModel = false


    override fun getLayout(): Int {
        return R.layout.activity_story_detail
    }

    override fun initPresenter(intent: Intent) {
        mPresenter = StoryDetailsPresenter(this,this,intent)
        setScheme()
        mPresenter.getStoryDetails()
    }

    /**
     * 设置App外部调用传递的参数
     */
    private fun setScheme() {
        val uri = intent.data
        if (uri != null) {
            val novelId = uri.getQueryParameter("id")
            if (!TextUtils.isEmpty(novelId)) {
                if (novelId != null) {
                    mPresenter.id = novelId.toInt()
                }
            }
        }
    }



    override fun initView() {
//        setStatusBarFullTransparent()
        setShareTipAnimation()
        mRefreshLayout.setOnRefreshListener {
            mPresenter.getStoryDetails()
        }
        mRefreshLayout.setOnLoadmoreListener {
            mPresenter.getCommentList(false)
        }
        tvAttention.setOnClickListener {
            if (!AccountService.getInstance().checkAndLogin()) {
                return@setOnClickListener
            }
            if (tvAttention.text.toString() == "取关..." || tvAttention.text.toString() == "关注..."){
                return@setOnClickListener
            }
            if (mPresenter.hasAttention){
                tvAttention.text = "取关..."
            }else{
                tvAttention.text = "关注..."
            }
            mPresenter.attentionUser()
        }
        ivAuthorHead.setOnClickListener {
            if (!TextUtils.isEmpty(mPresenter.novelBean.user.userId)){
                UserDetailActivity.startActivity(this@StoryDetailsActivity,mPresenter.novelBean.user.userId.toInt())
            }
        }

        layInput.setOnClickListener {
            showEditContent()
        }

        layBg.setOnClickListener {
            hideEditContent()
        }

        tvSend.setOnClickListener {
            if (!AccountService.getInstance().isLogin){
                AccountService.getInstance().jumpToLogin()
                return@setOnClickListener
            }
            if (etContent.text.isNotEmpty()) {
                //发布评论
                mPresenter.sendComment(etContent.text.toString())
            }else{
                Toast.makeText(this,"请输入评论内容",Toast.LENGTH_LONG).show()
            }
        }


        layShare.setOnClickListener {
//            shareMore()
            shareSystemDialog()
        }
        layShareMore.setOnClickListener {
//            shareMore()
            shareSystemDialog()
        }
        layShareWeixin.setOnClickListener {
            shareEvent(ShareType.Weixin)
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.Weixin
            ShareUtils.thirdPartyShare(this@StoryDetailsActivity,shareBean)
        }
        layShareWeibo.setOnClickListener {
            shareEvent(ShareType.Weibo)
            val shareBean = mPresenter.getShareBean()
            shareBean.shartText = getWeiboShareText()
            shareBean.social_type = ShareType.Weibo
            ShareUtils.thirdPartyShare(this@StoryDetailsActivity,shareBean)
        }
        layShareQQ.setOnClickListener {
            shareEvent(ShareType.QQ)
            val shareBean = mPresenter.getShareBean()
            shareBean.social_type = ShareType.QQ
            ShareUtils.thirdPartyShare(this@StoryDetailsActivity,shareBean)
        }
        layComment.setOnClickListener {
            scrollToComment()
        }
    }

    private fun shareEvent(socialType: Int) {
        val map = HashMap<String, String>()
        map["type"] = "$socialType"
        TMAnalysis.event(this@StoryDetailsActivity, UmengEventName.NOVEL_DETAIL_SHARE_ACTION, map)
    }

    fun formatContent(input:String):String {
        var content = input.trim()
        if (TextUtils.isEmpty(content)) {
            return ""
        }
        content = content.replace("　".toRegex(), "")
        content = content.replace(" ".toRegex(), "")
        content = content.replace(" ".toRegex(), "")
        content = content.replace("\t".toRegex(), "")
        content = content.replace("\n\n\n\n".toRegex(), "\n")
        content = content.replace("\n\n\n".toRegex(), "\n")
        content = content.replace("\n\n".toRegex(), "\n")
        content = content.replace("\r\n".toRegex(), "\n")
        return content
    }



    private fun setShareTipAnimation() {
        setTipViewAnimation(ivShareTip,ScreenUtil.dip2px(this,38f).toFloat(),0f)
    }

    private fun setTipViewAnimation(view:View,x:Float,y:Float) {

        val animationAlphaStart = ObjectAnimator.ofFloat(view,"alpha",0f,1f)
        animationAlphaStart.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator?) {
                super.onAnimationEnd(animation)
                val animationEnd = ObjectAnimator.ofFloat(view,"alpha",1f,0f)
                animationEnd.duration = 500
                animationEnd.startDelay = 3000
                animationEnd.start()
            }
        })
        val animationScaleX = ObjectAnimator.ofFloat(view,"scaleX",0f,1f)
        val animationScaleY = ObjectAnimator.ofFloat(view,"scaleY",0f,1f)
        view.pivotX = x
        view.pivotY = y
        val animationSet = AnimatorSet()
        animationSet.duration = 500
        animationSet.startDelay = 1000
        animationSet.play(animationAlphaStart).with(animationScaleX).with(animationScaleY)
        animationSet.start()
    }

    override fun onPause() {
        try {
            uploadRecord()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        super.onPause()
    }

    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    fun uploadRecord() {
        val record = ReadRecord()
        record.type = Constant.OBJECT_TYPE_NOVEL
        record.novel_id = "${mPresenter.id}"
        record.position = 1
        record.all_num = 1
        record.time  = dateFormat.format(Date())
        record.name = mPresenter.novelBean.title
        ReadHistoryUtil.addOrUpdateData(record)
    }

    private fun shareSystemDialog() {
        val shareBean = mPresenter.getShareBean()
        val desc = "我正在 豆花 App 看《" + shareBean.title + "》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! " + shareBean.shareUrl
        ShareUtil.shareText(this, shareBean.title, desc)
    }

    private fun shareMore() {
        if (shareDialog == null) {
            shareDialog = ShareUtils.getBottomDialog(this,false,object :ShareUtils.OnClickListener{
                override fun onClickHelp() {
                    BrowseActivity.startActivity(thisActivity,"https://api.doufu.la/journal/detail?id=745")
                }

                override fun onClickItem(social_type: Int) {
                    val map = HashMap<String, String>()
                    map["type"] = "$social_type"
                    TMAnalysis.event(this@StoryDetailsActivity, UmengEventName.NOVEL_DETAIL_MORE_SHARE_ACTION, map)
                    when (social_type) {
                        ShareType.CopyLink -> ShareUtils.copyLike(this@StoryDetailsActivity,mPresenter.getShareBean().shareUrl)
                        ShareType.Weibo ->{
                            val shareBean = mPresenter.getShareBean()
                            shareBean.shartText = getWeiboShareText()
                            shareBean.social_type = social_type
                            ShareUtils.thirdPartyShare(this@StoryDetailsActivity,shareBean)
                        }
                        ShareType.Poster->{
                            StoryPosterActivity.startActivity(thisActivity,mPresenter.novelBean)
                        }
                        else -> {
                            val shareBean = mPresenter.getShareBean()
                            shareBean.social_type = social_type
                            ShareUtils.thirdPartyShare(this@StoryDetailsActivity,shareBean)
                        }
                    }
                }
            })
//            shareDialog?.findViewById<View>(R.id.layMakePoster)?.visibility = View.INVISIBLE
        }
        shareDialog?.show()
    }


    fun getWeiboShareText() :String{
        var text = "我在#豆花# 发现了一篇超好看的小短篇，【${mPresenter.novelBean.title}】作者：【${mPresenter.novelBean.user.name}】快来看>${mPresenter.novelBean.shareUrl} #短文# #推文#"
        mPresenter.novelBean.tags.forEach {
            text+="#${it.name}#"
        }
        return text
    }

    private fun setTags(tags:MutableList<TagBean>) {
        layStoryTag.setViewMarginHorizontal(ScreenUtil.dip2px(this, 8f))
        layStoryTag.setViewMarginVertical(ScreenUtil.dip2px(this,9f))
        if (tags != null) {
            layStoryTag.removeAllViews()
            for (i in tags.indices) {
                val text = TextView(this)
                text.setOnClickListener {
                    TagsUtil.openWeexTagActivity(thisActivity,tags[i].name, Constant.OBJECT_TYPE_NOVEL,1)
                }
                text.isClickable = true
                val params = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
                text.layoutParams = params
                text.textSize = 11f
                text.text = tags[i].name
                text.gravity = Gravity.CENTER
                text.setTextColor(ContextCompat.getColor(this,R.color.text_color_8993A3))
                text.setBackgroundResource(R.drawable.bg_tag_gray)
                text.setPadding(ScreenUtil2.dip2px(7f), ScreenUtil2.dip2px(1f), ScreenUtil2.dip2px(7f), ScreenUtil2.dip2px(1f))
                layStoryTag.addView(text)
            }
        }
    }

    fun scrollToComment() {
        val margin = ScreenUtil.dip2px(this,64f)
        val y = tvTitle.height+ivAuthorHead.height+tvInfo.height+tvContent.height+layTag.height+layShareEnter.height+margin
        svContent.smoothScrollTo(0,y)
    }


    override fun sendComment(success: Boolean) {
        if (success) {
            etContent.setText("")
            hideEditContent()
            mPresenter.getCommentList(true)
            Toast.makeText(this,"评论成功",Toast.LENGTH_LONG).show()
            scrollToComment()
        }
    }

    override fun getCommentList(isRefresh: Boolean, list: MutableList<NovelCommentBean>) {
        if (isRefresh) {
            mRefreshLayout.finishRefresh()
        }else{
            mRefreshLayout.finishLoadmore()
        }
        if (isRefresh) {
            commentAdapter?.setData(list)
        }else{
            commentAdapter?.addData(list)
        }
        if (commentAdapter?.dataList == null || commentAdapter?.dataList?.size == 0) {
            tvCommentNull.visibility = View.VISIBLE
            rvComment.visibility = View.GONE
        }else{
            tvCommentNull.visibility = View.GONE
            rvComment.visibility = View.VISIBLE
        }
    }



    private fun setYouthModel() {
        val pwd = DiaoBaoSharedPreferences.getSharedPreferencesValueToString(SPKey.YOUTH_MODEL_PWD, this, "")
        if (pwd != null && pwd.isNotEmpty()) {
            isYouthModel = true
            layTag.visibility = View.GONE
        }
    }

    override fun fillNovelDetail(bean: NovelDetailBean) {
        commentAdapter = NovelHotCommentAdapter(this,bean.user.userId,object :NovelHotCommentAdapter.OnClickPraiseListener{
            override fun onClick(id: Int, position: Int, cancel: Boolean) {
                if (!AccountService.getInstance().checkAndLogin()) {
                    return
                }
                //点赞
                mPresenter.praiseComment(id,position,cancel)
            }
        })
        rvComment.layoutManager = object :LinearLayoutManager(this){
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        layMore.setOnClickListener {
            toastMoreDialog()
        }
        rvComment.adapter = commentAdapter
        tvCommentCount.text = "${if (bean.comment_times.toInt()>0) bean.comment_times else "评论"}"
        tvTitle.text = bean.title
        tvUserName.text = "${bean.user.name}"
        tvInfo.text = "${bean.length}字 ${bean.read_times.toInt().format()}阅读"
        tvTime.text = "${TimeDateFunction.toDateTime(bean.update_time*1000)}"
        TextUtil.setParagraphSpacing(this,tvContent,formatContent(bean.description),14,0)
        setTags(bean.tags)
        GlideUtil.displayCircleImage(ivAuthorHead,bean.user.icon)
        setAttention(if (bean.user.following.isNullOrEmpty()) false else bean.user.following.toInt() > 0)
        setYouthModel()
    }



    private fun setAttention(isAttention: Boolean) {
        if (isAttention) {
            tvAttention.text = "已关注"
            tvAttention.setTextColor(ContextCompat.getColor(this,R.color.text_color_57))
            tvAttention.setBackgroundResource(R.drawable.cycle_red_light)
        }else{
            tvAttention.text = "+关注"
            tvAttention.setTextColor(ContextCompat.getColor(this,R.color.white))
            tvAttention.setBackgroundResource(R.drawable.cycle_red)
        }
    }

    override fun attentionUser(cancel: Boolean, success: Boolean) {
        if (cancel) {
            //取消关注
            if (success){
                setAttention(false)
            }else{
                setAttention(true)
            }
        }else{
            if (success) {
                setAttention(true)
            }else{
                setAttention(false)
            }
        }
    }

    override fun praiseComment(position: Int, cancel: Boolean, success: Boolean) {
        if (success && commentAdapter != null && commentAdapter?.dataList?.size!! > position) {
            if (cancel) {
                commentAdapter!!.dataList[position].like_times-=1
                commentAdapter!!.dataList[position].has_liked = 0
            }else{
                commentAdapter!!.dataList[position].has_liked = 1
                commentAdapter!!.dataList[position].like_times+=1
            }
            commentAdapter!!.notifyDataSetChanged()
        }
    }


    fun toastMoreDialog() {
        val dialog = BottomSheetDialog(this)
        dialog.setContentView(R.layout.dialog_bottom_story_detail_more)
        val tvCancel = dialog.findViewById<View>(R.id.tvCancel)
        val tvReport = dialog.findViewById<View>(R.id.tvReport)
        val tvShare = dialog.findViewById<View>(R.id.tvShare)

        tvReport?.setOnClickListener {
            HomeMainServices.reportContentRequest(this, mPresenter.novelBean.user.userId, "${mPresenter.novelBean.object_type}", "")
            dialog.dismiss()
        }
        tvShare?.setOnClickListener {
            shareSystemDialog()
//            shareMore()
            dialog.dismiss()
        }
        tvCancel?.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }

    override fun showErrorView(error: String) {
        mRefreshLayout.finishRefresh()
    }

    fun showEditContent() {
        layEditContent.visibility = View.VISIBLE
        layBg.visibility = View.VISIBLE
        SoftKeyboardUtil.showInput(this,etContent)
    }

    fun hideEditContent() {
        SoftKeyboardUtil.hideSoftKeyboard(thisActivity)
        layEditContent.visibility = View.GONE
        layBg.visibility = View.GONE
    }


    override fun onBackPressed() {
        if (layBg.visibility == View.VISIBLE) {
            hideEditContent()
        }else{
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    companion object{

        fun startActivity(context: Context, novelId: String) {
            if (!novelId.isNullOrEmpty()) {
                startActivity(context,novelId.toInt())
            }
        }

        fun startActivity(context: Context, novelId: String, flag: Int) {
            if (!novelId.isNullOrEmpty()) {
                startActivity(context,novelId.toInt(),flag)
            }
        }

        fun startActivity(context: Context, novelId: Int) {
            val intent = Intent(context, StoryDetailsActivity::class.java)
            intent.putExtra(Constant.ID, novelId)
            context.startActivity(intent)
        }

        fun startActivity(context: Context, novelId: Int, flag: Int) {
            val intent = Intent(context, StoryDetailsActivity::class.java)
            intent.putExtra(Constant.ID, novelId)
            intent.flags = flag
            context.startActivity(intent)
        }
    }

}